package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ForumAdminRelationDao;
import com.example.simpleforum.dao.ForumApplicationDao;
import com.example.simpleforum.dao.ForumDao;
import com.example.simpleforum.dao.UserDao;
import com.example.simpleforum.model.Forum;
import com.example.simpleforum.model.ForumApplication;
import com.example.simpleforum.model.ForumAdminRelation;
import com.example.simpleforum.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 板块申请审核Servlet
 */
public class ForumApplicationReviewServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null || user.getRole() != User.Role.main_admin) {
            // 用户未登录或不是主管理员，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取所有待处理的申请
        ForumApplicationDao applicationDao = new ForumApplicationDao();
        request.setAttribute("applications", applicationDao.findPendingApplications());
        
        // 转发到审核页面
        request.getRequestDispatcher("/forumApplicationReview.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User reviewer = (User) session.getAttribute("user");
        
        if (reviewer == null || reviewer.getRole() != User.Role.main_admin) {
            // 用户未登录或不是主管理员，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取表单参数
        int applicationId = Integer.parseInt(request.getParameter("applicationId"));
        String action = request.getParameter("action");
        String reviewNotes = request.getParameter("reviewNotes");
        
        // 获取申请信息
        ForumApplicationDao applicationDao = new ForumApplicationDao();
        ForumApplication application = applicationDao.findById(applicationId);
        
        if (application == null) {
            request.setAttribute("error", "申请不存在");
            doGet(request, response);
            return;
        }
        
        // 处理审核
        boolean success = false;
        String message = "";
        
        if ("approve".equals(action)) {
            // 批准申请
            success = applicationDao.updateApplicationStatus(
                applicationId, 
                ForumApplication.Status.approved, 
                reviewer.getId(), 
                reviewNotes
            );
            
            if (success) {
                // 判断是申请创建新板块还是申请管理已有板块
                if (application.getForumId() == null) {
                    // 申请创建新板块，先创建板块
                    ForumDao forumDao = new ForumDao();
                    Forum forum = new Forum(
                        application.getForumName(),
                        application.getForumDescription(),
                        application.getApplicantId()
                    );
                    int forumId = forumDao.createForum(forum);
                    
                    if (forumId > 0) {
                        // 将申请人设为板块管理员
                        ForumAdminRelationDao relationDao = new ForumAdminRelationDao();
                        ForumAdminRelation relation = new ForumAdminRelation(
                            forumId, 
                            application.getApplicantId(), 
                            reviewer.getId()
                        );
                        success = relationDao.addAdminRelation(relation);
                        
                        if (success) {
                            // 更新用户角色为板块管理员
                            UserDao userDao = new UserDao();
                            success = userDao.updateUserRole(application.getApplicantId(), User.Role.forum_admin);
                            message = "申请已批准，板块已创建，用户已成为板块管理员";
                        } else {
                            message = "板块创建成功，但无法设置板块管理员";
                        }
                    } else {
                        message = "批准申请时出错，无法创建板块";
                        success = false;
                    }
                } else {
                    // 申请管理已有板块
                    // 将申请人设为板块管理员
                    ForumAdminRelationDao relationDao = new ForumAdminRelationDao();
                    ForumAdminRelation relation = new ForumAdminRelation(
                        application.getForumId(), 
                        application.getApplicantId(), 
                        reviewer.getId()
                    );
                    success = relationDao.addAdminRelation(relation);
                    
                    if (success) {
                        // 更新用户角色为板块管理员
                        UserDao userDao = new UserDao();
                        success = userDao.updateUserRole(application.getApplicantId(), User.Role.forum_admin);
                        message = "申请已批准，用户已成为板块管理员";
                    } else {
                        message = "批准申请时出错，无法设置板块管理员";
                    }
                }
            } else {
                message = "批准申请失败";
            }
        } else if ("reject".equals(action)) {
            // 拒绝申请
            success = applicationDao.updateApplicationStatus(
                applicationId, 
                ForumApplication.Status.rejected, 
                reviewer.getId(), 
                reviewNotes
            );
            message = "申请已拒绝";
        }
        
        if (success) {
            request.setAttribute("success", message);
        } else {
            request.setAttribute("error", message);
        }
        
        // 转发回审核页面
        doGet(request, response);
    }
}